package com.liao.product.controller;

import com.liao.common.entity.product.CategoryEntity;
import com.liao.product.service.CategoryService;
import com.liao.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * 商品分类体系（支持三级分类）
 *
 * @author liao
 * @email 2858015963@qq.com
 * @date 2025-02-13 13:26:53
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;


    /**
     * 树形列表
     */
    @RequestMapping("/list/tree")
    public List<CategoryEntity> listByTree() {
        return categoryService.listWithTree();
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public List<CategoryEntity> list() {
        return categoryService.list();

    }

    /**
     * 根据分类id获取所有id集合
     */
    @RequestMapping("/getIdListById")
    public List<Integer> getIdListById(@RequestParam Integer catregoryId) {
        return categoryService.getIdListById(catregoryId);

    }

    /**
     * 信息
     */
    @RequestMapping("/info/{categoryId}")
    public CategoryEntity info(@PathVariable("categoryId") Integer categoryId) {
        return categoryService.getById(categoryId);

    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public void save(@RequestBody CategoryEntity category) {
        categoryService.save(category);

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public void update(@RequestBody CategoryEntity category) {
        categoryService.updateById(category);

    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public void delete(@RequestBody Integer[] categoryIds) {


        for (Integer categoryId : categoryIds) {
            //判断该分类下是否有商品
            int count = productService.getProductCountByCategoryId(categoryId);

            if (categoryService.hasChild(categoryId)) {
                throw new RuntimeException("该分类下有子分类，不能删除");
            }

            if (count > 0) {
                throw new RuntimeException("该分类下有商品，不能删除");
            }


        }
        categoryService.removeByIds(Arrays.asList(categoryIds));

    }

    /**
     * 首页-前台分类
     *
     * @apiNote 小程序查询前台分类，只查询一级类目信息
     */
    @GetMapping("/mutli")
    public List<CategoryEntity> getMutli() {
        return categoryService.getMutli();
    }

}
